from ctypes import *
from distutils.sysconfig import get_python_lib

try:
    quartetLib = cdll.LoadLibrary("./libpyQuartetDist.so")
    quartetLibraryLocation = "./libpyQuartetDist.so"
    tripletLib = cdll.LoadLibrary("./libpyTripletDist.so")
    tripletLibraryLocation = "./libpyTripletDist.so"
except OSError: ## fix
    python_lib = get_python_lib()
    quartetLib = cdll.LoadLibrary(python_lib + "/libpyQuartetDist.so")
    tripletLib = cdll.LoadLibrary(python_lib + "/libpyTripletDist.so")
    quartetLibraryLocation = python_lib + "/libpyQuartetDist.so"
    tripletLibraryLocation = python_lib + "/libpyTripletDist.so"
except OSError as e:
    print "Error: libpyQuartetDist.so or libpyTripletDist.so not found:"
    print "Looked in:", python_lib, '/libpyTQDist.so and ./'
    print "{0}: {1}".format(e.errno, e.strerror)
    exit(-1)


tripletLib.tripletDistance.restype = c_ulong
def tripletDistance(filename1, filename2):
    return tripletLib.tripletDistance(c_char_p(filename1), c_char_p(filename2))

tripletLib.allPairsTripletDistance.restype = py_object
def allPairsTripletDistance(filename): ## Disclaimer: ugly ugly hack, because integer comparison is weird in Python
    res = tripletLib.allPairsTripletDistance(c_char_p(filename))
    result = []
    for ls in res:
        current = []
        for x in ls:
            current.append(int(str(x)))
        result.append(current)
    return result

quartetLib.quartetDistance.restype = c_ulong
def quartetDistance(filename1, filename2):
    return quartetLib.quartetDistance(c_char_p(filename1), c_char_p(filename2))

quartetLib.allPairsQuartetDistance.restype = py_object
def allPairsQuartetDistance(filename): ## Disclaimer: ugly ugly hack, because integer comparison is weird in Python
    res = quartetLib.allPairsQuartetDistance(c_char_p(filename))
    result = []
    for ls in res:
        current = []
        for x in ls:
            current.append(int(str(x)))
        result.append(current)
    return result
